package com.team.instantsharing.management

import java.security.SignatureException
import com.amazonaws.util.json.JSONObject
import com.sun.xml.internal.org.jvnet.staxex.Base64Encoder
import com.team.instantsharing.dto.Message
import com.team.instantsharing.dto.File;

import grails.converters.JSON

import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.ServiceRequest;

import java.security.SignatureException;
import java.text.DateFormat
import java.text.SimpleDateFormat

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.groovy.grails.web.json.JSONArray
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.springframework.web.client.RestTemplate

import sun.misc.BASE64Encoder

class PhotoController {
	
	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
	private static final String secretKey = "BzJXJ1hMKQsRfpfxMZlPbJBlUgcKa3DrKx1iJb+J";
	private static final String accessKeyId = "AKIAJPGSDIIFNSVSL6AA";
	public static String generateHMAC(String data, String secretKey)throws java.security.SignatureException {
		String resultSigningKey = null;
		try {
			SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(),HMAC_SHA1_ALGORITHM);
			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data.getBytes());
			resultSigningKey = new String(Base64.encodeBase64(rawHmac));
		} catch (Exception e) {
			throw new SignatureException("Failed to generate HMAC : "+ e.getMessage());
		}
		return resultSigningKey;
	}
	
    def index() {
		
		if (session.userEmail == null || session.userEmail == ""){
			redirect controller:'home', action: 'index';
			return;
		}
		
		
		String bucketS3 = Constant.AMAZON_BUCKET;
		String accessKeyId = "AKIAJPGSDIIFNSVSL6AA";
		String secretKey = "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";
		String aclPermission = "public-read";
		String successStatus = "201";
		String policyS3 = null;
		String base64Policy = null;
		String signature = null;
		String key = "\$"+"key";
		
		JSONObject bucket = new JSONObject();
		bucket.put("bucket", bucketS3);

		JSONObject acl = new JSONObject();
		acl.put("acl", aclPermission);
		
		JSONObject status = new JSONObject();
		status.put("success_action_status", successStatus);
		
		String folderPath = session.userEmail+"/";
		println folderPath;
		JSONArray pathFolderandFile = new JSONArray();
		pathFolderandFile.add("starts-with");
		pathFolderandFile.add(key);
		pathFolderandFile.add(folderPath);

		JSONArray conditions = new JSONArray();
		conditions.add(bucket);
		conditions.add(acl);
		conditions.add(status);
		conditions.add(pathFolderandFile);

		DateTime output = new DateTime(DateTimeZone.UTC);
		
		output = output.plusHours(6);
		
		JSONObject objPolicy = new JSONObject();
		objPolicy.put("expiration", output.toString());
		objPolicy.put("conditions", conditions);
		
		byte[] bytesEncoded = Base64.encodeBase64(objPolicy.toString().getBytes());

		base64Policy = new String(bytesEncoded);
		
		try {
			signature = generateHMAC(base64Policy,secretKey);
		} catch (SignatureException e) {
			e.printStackTrace();
		}
		
		/*long offset = 0;
		List<File> listImages = getListImage(offset);*/
		
		 [
			bucketS3 : bucketS3,
			accessKeyId : accessKeyId,
			secretKey: secretKey,
			aclPermission : aclPermission,
			base64Policy :  base64Policy,
			signature : signature,
			folderPath : folderPath,
			/*listImages: listImages,
			offset : offset*/
		]
		 
		 
	
		 
	}
	 def _uploadImageForm(){
		 
	 }
	
	 private List<File> getListImage(long offset){
		 RestTemplate restTemplate = new RestTemplate();
		 List<File> listImages = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_LIST_IMAGES + "?userEmail="+ session.userEmail+"&offset="+offset, File[].class);
		 
		 if(listImages != null && !listImages.isEmpty()){
			 
			 if(listImages.get(0).getUserEmail().equals(session.userEmail)){
				
				 return listImages;
			 }
			 
		 }
		 
		 return listImages;
	 }
	 
	 
	 def getListNextImagesTotal(){
		 
		 
		 String bucketS3 = Constant.AMAZON_BUCKET;
		 long offset = Long.parseLong(params.thisoffset);
		 RestTemplate restTemplate = new RestTemplate();
		 List<File> listImages = restTemplate.getForObject(Constant.SERVICE_URL + ServiceRequest.GET_LIST_IMAGES + "?userEmail="+ session.userEmail+"&offset="+offset, File[].class);
		 long expiresTime = calEpochTime();
		 
		 if(listImages != null && !listImages.isEmpty()){
			 //if(listImages.get(0).getUserEmail().equals(session.userEmail)){
				 
				 offset += 6;
				/* String[] timeStartFormatted = new String[listImages.size()];
				 
				 for (int i = 0; i < listImages.size(); i++) {
					 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					 Date date = sdf.parse(listImages.get(i).getDateCreate());
					 timeStartFormatted[i] = date.format("HH:mm dd/MM/yyyy");
				 }*/
				/* for(File image : listImages){	
					 //image.setFileName(URLEncoder.encode(image.getFileName(),"UTF-8"));
					 if(!image.getFilePath().isEmpty()){
						 image.setFilePath(image.getUserEmail()+"/"+image.getFilePath()+"/");
					 }
					 if( image.getFilePath() == null || image.getFilePath().isEmpty()){
						 image.setFilePath(image.getUserEmail()+"/");
					 }
				 }*/
				 
				 for(File image : listImages){
					 
					 String	filePath =   URLEncoder.encode(image.getFilePath(), "UTF-8");
					 println "\n-ne"+filePath;
					 String fileName = URLEncoder.encode(image.getFileName(), "UTF-8");
					 image.setFilePath(filePath);
					 image.setFileName(fileName);
					 String autho;
					 if(filePath.isEmpty()){
						 autho = "GET\n\n\n"+expiresTime+"\n/cloudsharingpublic/"+image.getUserEmail()+ Constant.SUFFIX + fileName;
					 } else {
					 	autho = "GET\n\n\n"+expiresTime+"\n/cloudsharingpublic/"+image.getUserEmail()+ Constant.SUFFIX+ filePath + Constant.SUFFIX + fileName;
					 }
					
					 String signature = generateHMAC(autho,secretKey);
					 image.setAccessKeyId(accessKeyId);
					 image.setExpires(expiresTime.toString());
					 image.setSignature(URLEncoder.encode(signature, "UTF-8"));
					 
				 }
				 
				 
				 [offsetnext : offset,listImages : listImages,bucketS3:bucketS3]
			 }
			 
		 //}
	 }
	 
	 def gallery() {
		 
		 if (session.userEmail == null || session.userEmail == ""){
			 redirect controller:'home', action: 'index';
			 return;
		 }
		 
		 String bucketS3 = Constant.AMAZON_BUCKET;
		 String accessKeyId = "AKIAJPGSDIIFNSVSL6AA";
		 String secretKey = "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";
		 String aclPermission = "public-read";
		 String successStatus = "201";
		 String policyS3 = null;
		 String base64Policy = null;
		 String signature = null;
		 String key = "\$"+"key";
		 
		 JSONObject bucket = new JSONObject();
		 bucket.put("bucket", bucketS3);
 
		 JSONObject acl = new JSONObject();
		 acl.put("acl", aclPermission);
		 
		 JSONObject status = new JSONObject();
		 status.put("success_action_status", successStatus);
		 
		 String folderPath = params.userEmail+"/";
	 
		 JSONArray pathFolderandFile = new JSONArray();
		 pathFolderandFile.add("starts-with");
		 pathFolderandFile.add(key);
		 pathFolderandFile.add(folderPath);
 
		 JSONArray conditions = new JSONArray();
		 conditions.add(bucket);
		 conditions.add(acl);
		 conditions.add(status);
		 conditions.add(pathFolderandFile);
 
		 DateTime output = new DateTime(DateTimeZone.UTC);
		 
		 output = output.plusHours(6);
		 
		 JSONObject objPolicy = new JSONObject();
		 objPolicy.put("expiration", output.toString());
		 objPolicy.put("conditions", conditions);
		 
		 byte[] bytesEncoded = Base64.encodeBase64(objPolicy.toString().getBytes());
 
		 base64Policy = new String(bytesEncoded);
		 
		 try {
			 signature = generateHMAC(base64Policy,secretKey);
		 } catch (SignatureException e) {
			 e.printStackTrace();
		 }
		 
		 long offset = 0;
		 List<File> listImages = getListImage(offset);
		 
		  [
			 bucketS3 : bucketS3,
			 accessKeyId : accessKeyId,
			 secretKey: secretKey,
			 aclPermission : aclPermission,
			 base64Policy :  base64Policy,
			 signature : signature,
			 folderPath : folderPath,
			 listImages: listImages,
			 offset : offset
		 ]
		  
	 }
	 
	 def DeleteImage(){
		 String imageName = params.ImageName;
		 long imageId = (Long).parseLong(params.ImageId);
		/* RestTemplate restTemplate = new RestTemplate();
		 Message imageResponse = restTemplate.postForObject(Constant.SERVICE_URL + "/file/delete?imageName="+imageName+"&imageId="+imageId, Message.class);

		 [status : imageResponse.response]
		 */
		 [status : "11"]
	 }
	 
	 def Sharephoto(){

		String fileName = null;
		String filePath = params.url;
		String bucketS3 = Constant.AMAZON_BUCKET;
		if(filePath != null && filePath.contains("/")){
			List<String> fileImage = filePath.toString().split("/");
			fileName = java.net.URLDecoder.decode(fileImage.get(fileImage.size()-1), "UTF-8");
		}
		[fileName:fileName,filePath:filePath,bucketS3:bucketS3]
		 
	 }
	 
	 private static long calEpochTime(){
		 Date currentDate = new Date();
		 Date tomorrow = currentDate.plus(1); 
		 long epochTime = (tomorrow.getTime())/1000;
	 	  println epochTime;
		 return epochTime;
	 	
	 }
}